package com.lagou.edu.utils;


import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;


/**
 * 扫描工具
 */
public class ScanPackageUtils {

    private static List<Class<?>> classInfo = new ArrayList<>();

    /**
     * 扫描的class
     *
     * @param packageName
     */
    public static List<Class<?>> getResources(String packageName) throws IOException, ClassNotFoundException {
        String packageDirName = packageName.replace('.', '/');
        Enumeration<URL> resources = ScanPackageUtils.class.getClassLoader().getResources(packageDirName);
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            String protocol = url.getProtocol();
            if ("file".equals(protocol)) {
                String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                findAndAddClassesInPackageByFile(packageName, filePath);
            }
        }
        return classInfo;
    }

    /**
     * 以文件的形式来获取包下的所有Class
     * @param packageName
     * @param packagePath
     */
    public static void findAndAddClassesInPackageByFile(String packageName, String packagePath) throws ClassNotFoundException {
        File dir = new File(packagePath);
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }
        File[] dirfiles = dir.listFiles(file -> (file.isDirectory()) || (file.getName().endsWith(".class")));
        for (File file : dirfiles) {
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath());
            } else {
                String className = file.getName().substring(0, file.getName().length() - 6);
                classInfo.add(Class.forName(packageName + '.' + className));
            }
        }
    }
}
